package com.daxidi.cn.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxidi.cn.annotation.LogAnnotation;
import com.daxidi.cn.cons.ShgCons;
import com.daxidi.cn.entity.Log;
import com.daxidi.cn.entity.Manager;
import com.daxidi.cn.enums.LogTypeEnum;
import com.daxidi.cn.mapper.LogMapper;
import com.daxidi.cn.mapper.ManagerMapper;
import com.daxidi.cn.params.ChangeManagePwdParam;
import com.daxidi.cn.service.IManagerService;
import com.daxidi.cn.utils.*;
import com.daxidi.cn.vo.LoginVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author wsh
 * @since 2020-11-09
 */
@Log4j
@Api(tags = "管理员模块接口")
@RestController
@RequestMapping("/api/v1/union/manager")
public class ManagerController {
    @Autowired
    private IManagerService managerService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private HttpServletRequest request;

    @ApiOperation(value = "管理员模块  添加接口")
    @ApiResponses({
            @ApiResponse(code = 156, message = "添加成功"),
            @ApiResponse(code = 157, message = "用户名已存在"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/")
    public ReturnResult addManager(@RequestBody Manager manager) {
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("username",manager.getUsername());
        Manager manager1 = managerMapper.selectOne(wrapper);
        if (manager1 != null) {
            log.error("添加失败，用户已存在");
            return ReturnResultUtils.returnFailMsg(157, "用户已存在");
        }
        Manager m = managerService.selectManagerByName(manager.getUsername());
        if (ObjectUtils.isEmpty(m)) {
            manager.setPasswrod(UuidUtils.sha1(manager.getPasswrod()));
            manager.setCreatedAt(new Date());
            manager.setUpdatedAt(null);
            manager.setDeletedAt(null);
            manager.setEnable(true);
            managerService.addManager(manager);
            return ReturnResultUtils.returnSuccess();
        } else {
            log.error("添加失败，用户名已存在");
            return ReturnResultUtils.returnFailMsg(157, "用户名已存在");
        }
    }

    @ApiOperation(value = "管理员模块  删除接口")
    @ApiResponses({
            @ApiResponse(code = 158, message = "删除成功"),
            @ApiResponse(code = 159, message = "删除失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @DeleteMapping("/{id}")
    public ReturnResult deleteManagerById(@PathVariable(value = "id") Integer id) {
        try {
            managerService.deleteManagerById(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("删除失败" + e);
            return ReturnResultUtils.returnFailMsg(159, "删除失败");
        }
    }

    @ApiOperation(value = "管理员模块  修改接口")
    @ApiResponses({
            @ApiResponse(code = 160, message = "修改成功"),
            @ApiResponse(code = 161, message = "修改失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("")
    public ReturnResult updateManagerById(@RequestBody Manager manager) {
        try {
            // 根据id获取修改的是哪个对象
            Manager managerr = managerService.selectManagerById(manager.getId());
            managerr.setDeletedAt(null);
            // 添加修改时间
            managerr.setUpdatedAt(new Date());
            if (!StringUtils.isEmpty(manager.getPasswrod())) {
                managerr.setPasswrod(UuidUtils.sha1(manager.getPasswrod()));
            }
            if (!StringUtils.isEmpty(manager.getManagerName())) {
                managerr.setManagerName(manager.getManagerName());
            }
            if (!StringUtils.isEmpty(manager.getUsername())) {
                QueryWrapper<Manager> wrapper = new QueryWrapper<>();
                wrapper.eq("username",manager.getUsername());
                Manager manager1 = managerMapper.selectOne(wrapper);
                if (manager1 != null && !manager.getId().equals(manager1.getId())) {
                    log.error("添加失败，用户已存在");
                    return ReturnResultUtils.returnFailMsg(157, "用户已存在");
                }
                managerr.setUsername(manager.getUsername());
            }
            if (!StringUtils.isEmpty(manager.getIsAdmin())) {
                managerr.setIsAdmin(manager.getIsAdmin());
            }
            if (!StringUtils.isEmpty(manager.getManagerMobile())) {
                managerr.setManagerMobile(manager.getManagerMobile());
            }
            if (!StringUtils.isEmpty(manager.getSex())) {
                managerr.setSex(manager.getSex());
            }
            managerService.updateManagerId(managerr);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改失败" + e);
            return ReturnResultUtils.returnFailMsg(161, "修改失败");
        }
    }

    @ApiOperation(value = "管理员模块  个人中心修改密码")
    @ApiResponses({
            @ApiResponse(code = 161, message = "修改失败"),
            @ApiResponse(code = 160, message = "旧密码输入错误"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/changePwd")
    public ReturnResult changePwd(@RequestBody ChangeManagePwdParam pwdParam) {
        Manager manager = managerMapper.selectById(pwdParam.getManagerId());
        if (!manager.getPasswrod().equals(UuidUtils.sha1(pwdParam.getOldPwd()))) {
            return ReturnResultUtils.returnFailMsg(160, "旧密码输入错误");
        }
        manager.setPasswrod(UuidUtils.sha1(pwdParam.getNewPwd()));
        try {
            managerMapper.updateById(manager);
            return ReturnResultUtils.returnSuccess("修改密码成功!");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改密码失败！" + e);
            return ReturnResultUtils.returnFailMsg(161, "修改密码失败!");
        }
    }

    @ApiOperation(value = "管理员模块  分页查询接口", notes = "count:  为 数据的总条数")
    @ApiResponses({
            @ApiResponse(code = 162, message = "查询成功"),
            @ApiResponse(code = 163, message = "查询失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping
    public ReturnResult selectManagersPage(@RequestParam(defaultValue = "1") Integer page,
                                           @RequestParam(defaultValue = "5") Integer limit,
                                           @RequestParam(value = "managerName", required = false) String managerName,
                                           @RequestParam(value = "beginTime", required = false) String beginTime,
                                           @RequestParam(value = "endTime", required = false) String endTime) {
        try {
            System.err.println(managerName);
            Map map = managerService.selectManagersPage(page, limit, managerName, beginTime, endTime);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(163, "查询失败");
        }

    }

    @ApiOperation(value = "管理员模块  根据Id查询接口")
    @ApiResponses({
            @ApiResponse(code = 162, message = "查询成功"),
            @ApiResponse(code = 163, message = "查询失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping(value = "/{id}")
    public ReturnResult queryManagerById(@PathVariable(value = "id") Long id) {
        try {
            Manager manager = managerMapper.selectById(id);
            return ReturnResultUtils.returnSuccess(manager);
        } catch (Exception e) {
            log.error("查询失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(163, "查询失败");
        }
    }

    @ApiOperation(value = "管理员模块  登录接口")
    @ApiResponses({
            @ApiResponse(code = 172, message = "登录成功"),
            @ApiResponse(code = 173, message = "登陆失败"),
            @ApiResponse(code = 174, message = "验证码错误"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/loginManager")
    public ReturnResult loginManager(@RequestBody LoginVo loginVo, HttpSession httpSession) {
        Long timestamp1 = System.currentTimeMillis();
        // 获取验证码字符串
        String code = (String) redisUtils.get("scode");
        // 判断验证码是否正确
        if (!code.equalsIgnoreCase(loginVo.getCode())){
            //返回错误信息
            return ReturnResultUtils.returnFailMsg(174, "验证码错误");
        }
        System.out.println(code);
        System.err.println(loginVo.getUsername());
        System.err.println(loginVo.getPassword());
        System.err.println(loginVo.getCode());

        // 根据username和password查询
        Manager managerr = managerService.loginManager(loginVo.getUsername(), UuidUtils.sha1(loginVo.getPassword()));
        //  如果 managerr!=null  则登录成功
        if (managerr != null) {
            // 把 mangerr 返回前端
            httpSession.setAttribute("manager", managerr);
            redisUtils.set("manager", loginVo.getUsername());
            //redisUtils.set(ShgCons.TOKEN_MANAGER + JWTUtils.generate(loginVo.getUsername()), JSON.toJSONString(managerr), 18000);
            HashMap map = new HashMap();
            map.put("manager", managerr);
            map.put("token", JWTUtils.generate(loginVo.getUsername()));
            //添加日志
            Log log = new Log();
            log.setLogAt(new Date(timestamp1));
            String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
            log.setLogIp(ipAddrByRequest);
            log.setLogContent("管理员登录");
            log.setLogTime(System.currentTimeMillis() - timestamp1);
            log.setLogType("SELECT");
            log.setUsername(StringUtils.isEmpty(loginVo.getUsername()) ? "未添加的管理员名" : loginVo.getUsername());
            logMapper.insert(log);
            return ReturnResultUtils.returnSuccess(map);
        } else {
            //  否则登陆失败  返回失败信息
            log.error("用户名或密码错误");
            return ReturnResultUtils.returnFailMsg(173, "用户名或密码错误");
        }
    }

    @LogAnnotation(content = "重置管理员密码", type = LogTypeEnum.UPDATE)
    @ApiOperation(value = "重置管理员密码接口")
    @PutMapping("/updatePassword/{id}")
    public ReturnResult updatePassword(@PathVariable("id") Long id, HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            Claims claims = JWTUtils.getClaim(token);
            String name = claims.get("mobile").toString();
            QueryWrapper<Manager> wrapper = new QueryWrapper<>();
            wrapper.eq("username", name);
            Manager manager = managerMapper.selectOne(wrapper);
            if (ObjectUtils.isEmpty(manager)) {
                return ReturnResultUtils.returnFailMsg(631, "非管理员身份！");
            }

            QueryWrapper<Manager> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id", id);
            Manager manager1 = managerMapper.selectOne(wrapper1);
            manager1.setPasswrod(UuidUtils.sha1("123"));
            managerMapper.updateById(manager1);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("重置密码失败" + e);
            return ReturnResultUtils.returnFailMsg(115, "重置密码失败");
        }
    }
}
